package com.wanchuang.hepos.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.proto.Statistics;
import com.github.mikephil.charting.charts.Chart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.MPPointF;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MyLineChartView extends LineChart {
    public MyLineChartView(Context context) {
        super(context);
    }

    public MyLineChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        // 手势禁用
//         this.setTouchEnabled(false);
        this.setScaleEnabled(false); // 启用/禁用缩放图表上的两个轴。
        // 设置MarkerView
        LineChartMarkView mv = new LineChartMarkView(context);
        mv.setChartView(this);
        this.setMarker(mv);
        Description description = new Description();
        description.setText("");
        this.setDescription(description);
        //设置样式
        YAxis rightAxis = this.getAxisRight();
        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        YAxis LeftAxis = this.getAxisLeft();
        LeftAxis.setDrawGridLines(true);//设置为true，则绘制网格线。
        LeftAxis.setDrawAxisLine(false);//设置为true，则绘制该行旁边的轴线（axis-line）。
        LeftAxis.setDrawLabels(false);//设置为true，则绘制轴的标签。
        LeftAxis.setGridColor(Color.parseColor("#DCCACF"));
//        LeftAxis.setAxisMaximum(0);
        LeftAxis.setStartAtZero(true);//  设置Y轴是否从0开始
        LeftAxis.setLabelCount(5);  // 设置Y轴数据量
        //设置x轴
        XAxis xAxis = this.getXAxis();
        xAxis.setTextColor(Color.parseColor("#6F889C"));
        xAxis.setTextSize(11f);
//        xAxis.setGranularity(1);     // 整数对其
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setAxisLineColor(Color.parseColor("#DCCACF"));
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
//        xAxis.setGridColor(Color.parseColor("#26070707"));
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                if (value < getData().getEntryCount()) {
                    return getData().getDataSetByIndex(0).getEntryForIndex((int) value).getData().toString();  // 获取第一份数据DataSet
                } else {
                    return "";
                }
            }
        });

        //透明化图例
        Legend legend = this.getLegend();
        legend.setEnabled(false);
    }


    /**
     * 设置折线图数据
     */
    public void setLineData(List<Statistics.statistics> list) {
        //1.设置x轴和y轴的点
        List<Entry> entries = new ArrayList<>();
        float total = 0;
        for (int i = 0; i < list.size(); i++) {
            float number = Float.valueOf(list.get(i).getAmount());
            total = total > number ? total : number;
            String time = getStrTimeFormat(list.get(i).getTime(), "MM-dd");
            entries.add(new Entry(i, number, time));
        }
        YAxis LeftAxis = getAxisLeft();
        if (total == 0) { total = 100; }
        LeftAxis.setAxisMaximum(total * 1.4f);  // 防止超过顶部
        LineDataSet dataSet = new LineDataSet(entries, "趋势"); // add entries to dataset
        dataSet.setColor(Color.parseColor("#8A9EC1FF"));//线条颜色
        dataSet.setCircleColor(Color.parseColor("#28AFE9"));//圆点颜色
        dataSet.setDrawFilled(false);  // 设置是否填充
        dataSet.setDrawCircleHole(false);  // 设置是否实心
        dataSet.setLineWidth(1.0f);//线条宽度
        dataSet.setDrawValues(false);
        dataSet.setHighLightColor(Color.parseColor("#ffffff"));
        //3.chart设置数据
        LineData lineData = new LineData(dataSet);
        setData(lineData);
        animateY(500);
    }


    public String getStrTimeFormat(String cc_time, String format) {
        //同理也可以转为其它样式的时间格式.例如："yyyy/MM/dd HH:mm"
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        return sdf.format(new Date(lcc_time * 1000L));
    }




    public class LineChartMarkView extends MarkerView {
        private final int DEFAULT_INDICATOR_COLOR = 0xff618AE7;//指示器默认的颜色
        private final int ARROW_HEIGHT = dp2px(15); // 箭头的高度
        private final int ARROW_WIDTH = dp2px(15); // 箭头的宽度
        private final float ARROW_OFFSET = dp2px(2);//箭头偏移量
        private final float BG_CORNER = dp2px(4);//背景圆角
        private final float UP_HIGHT = dp2px(3);//背景圆角

        private TextView tvDate;
        private TextView tvValue0;
        private Paint bgPaint;
        private final Paint arrowPaint;

        public LineChartMarkView(Context context) {
            super(context, R.layout.layout_markview);
            tvDate = findViewById(R.id.tv_date);
            tvValue0 = findViewById(R.id.tv_value0);
            //指示器背景画笔
            bgPaint = new Paint();
            bgPaint.setStyle(Paint.Style.FILL);
            bgPaint.setAntiAlias(true);
            bgPaint.setColor(DEFAULT_INDICATOR_COLOR);
            //剪头画笔
            arrowPaint = new Paint(); // 剪头画笔
            arrowPaint.setStyle(Paint.Style.FILL);
            arrowPaint.setAntiAlias(true);
            arrowPaint.setColor(DEFAULT_INDICATOR_COLOR);

        }


        @SuppressLint("SetTextI18n")
        @Override
        public void refreshContent(Entry e, Highlight highlight) {
            Chart chart = getChartView();
            if (chart instanceof LineChart) {
                LineData lineData = ((LineChart) chart).getLineData();
                //获取到图表中的所有曲线
                List<ILineDataSet> dataSetList = lineData.getDataSets();
                for (int i = 0; i < dataSetList.size(); i++) {
                    LineDataSet dataSet = (LineDataSet) dataSetList.get(i);
                    //获取到曲线的所有在Y轴的数据集合，根据当前X轴的位置 来获取对应的Y轴值
                    float y = dataSet.getValues().get((int) e.getX()).getY();
                    tvValue0.setText(formatDouble(y));
                }
                tvDate.setText(e.getData().toString());
            }
            super.refreshContent(e, highlight);
        }

        @Override
        public MPPointF getOffset() {
            return new MPPointF(-(getWidth() / 2f), -getHeight());
        }


        @Override
        public void draw(Canvas canvas, float posX, float posY) {
            Chart chart = getChartView();
            if (chart == null) {
                super.draw(canvas, posX, posY);
                return;
            }


            float width = getWidth();
            float height = getHeight();

            int saveId = canvas.save();
            //移动画布到点并绘制点
            canvas.translate(posX, posY - UP_HIGHT);
            //画指示器
            // 画指示器
            Path path = new Path();
            RectF bRectF;
            //移动画布并绘制三角形和背景
            canvas.translate(0, -height - ARROW_HEIGHT);
            if (posX < width / 2f) {//超过左边界  平移view
                canvas.translate(width / 2f - posX, 0);
                /*************绘制三角形 超过下边界 /  超过左边界**/
                path.moveTo(-(width / 2f - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
                path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                path.lineTo(-ARROW_WIDTH / 2f, height - BG_CORNER);
                path.moveTo(-(width / 2f - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
            } else {
                if (posX > chart.getWidth() - (width / 2f)) {//超过右边界  绘制三角
                    /*************绘制三角形 超过下边界 /  超过右边界**/
                    canvas.translate(-(width / 2 - (chart.getWidth() - posX)), 0);
                    path.moveTo(width / 2 - (chart.getWidth() - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
                    path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                    path.lineTo(-ARROW_WIDTH / 2f, height - BG_CORNER);
                    path.moveTo(width / 2 - (chart.getWidth() - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);

                } else {
                    path.moveTo(0, height + ARROW_HEIGHT);
                    path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                    path.lineTo(-ARROW_WIDTH / 2f, height - BG_CORNER);
                    path.moveTo(0, height + ARROW_HEIGHT);
                }
            }
            bRectF = new RectF(-width / 2, 0, width / 2, height);
            canvas.drawPath(path, arrowPaint);
            canvas.drawRoundRect(bRectF, BG_CORNER, BG_CORNER, bgPaint);
            canvas.translate(-width / 2f, 0);
            draw(canvas);
            canvas.restoreToCount(saveId);
        }

        private int dp2px(int dpValues) {
            return (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, dpValues,
                    getResources().getDisplayMetrics());
        }

        private String formatDouble(float value) {
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            if (value >= 10000) {
                double n = value / 10000;
                return (decimalFormat.format(n) + "万");
            } else {
                return (decimalFormat.format(value));
            }
        }
    }

}
